import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class FreeMarkerStringRender {
    public static String renderTemplateString(Map<String, Object> context, String templateContent) throws Exception {
        // 1. 配置 FreeMarker
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        // 2. 使用字符串作为模板
        Template template = new Template("templateName", new StringReader(templateContent), cfg);

        // 3. 渲染
        StringWriter out = new StringWriter();
        template.process(context, out);

        return out.toString();
    }

    public static void main(String[] args) throws Exception {
        // 构造数据模型
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("user", "Alice");
        dataModel.put("items", new String[]{"Apple", "Banana", "Cherry"});

        // 模板内容（直接写在字符串里）
        String templateContent = """
            Hello ${user}!
            Here are your items:
            <#list items as item>
             - ${item}
            </#list>
            """;

        // 调用渲染方法
        String result = renderTemplateString(dataModel, templateContent);
        System.out.println(result);
    }
}
